import {createStore} from 'redux'
import Action from './action';
import {useSelector} from 'react-redux';
import {ROUTERCHANGE,CLOSE_ROUTERSTACK} from './reducer/routerReducer';


const getState = ():StateProps=>{
  let oldState:StateProps;
  let str = window.localStorage.getItem("redux-store")
  if(str){
    oldState = JSON.parse(str)
    return oldState
  }
  return {
    routerPath:"/",
    params:{
      query:{},
      state:{}
    },
    menuCollapsed:false,
    routerStack:[],
  }  
}
export const initState:StateProps = getState();

export interface ActionTypes{
  type:string,
  payload?:any,
}

export const reducer = (state=initState,action:ActionTypes)=>{
  switch (action.type){
    case Action.CHANGE_MENU:// 控制侧边栏展开和收缩
      state.menuCollapsed = !state.menuCollapsed;
      break;
    case Action.ROUTER_CHANGE:// 路由变化
      ROUTERCHANGE(state,action);
      break;
    case Action.CLOSE_ROUTERSTACK:
      CLOSE_ROUTERSTACK(state,action);
      break;
    case Action.INIT_ROUTER:
      state.routerPath = action.payload;
    default:
      break
  }
  const newState = {...state}
  /**同步sessionStorage中的数据 先移除在添加*/
  window.localStorage.removeItem("redux-store")
  window.localStorage.setItem("redux-store",JSON.stringify(newState));
  return newState
}

const store = createStore(reducer)


type disPatchType = (props:{type:string,payload:any})=>void;

export const useRedux = ()=>{
  const dispatch:disPatchType = (props)=>{
    const {type,payload} = props;
    store.dispatch({type:type,payload:payload});
  }
  return {
    state:useSelector((state:StateProps) => {
      return state
    }),
    dispatch:store.dispatch,
  }
}

export default store